package com.lipei.vrp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Opt {

	public double cost = -1;
	public ResultType resulttype = null;
	public AlgorithmType algtype = null;
	public ArrayList<ArrayList<Integer>> routes = new ArrayList<ArrayList<Integer>>();

	public static Opt optReader(String filename) throws IOException {
		File file = new File(filename);

		if (!file.exists()) {
			return null;
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(file)));

		ArrayList<String> list = new ArrayList<String>();
		while (true) {
			String line = reader.readLine();
			if (line != null) {
				list.add(line);
			} else {
				break;
			}
		}
		reader.close();

		Opt opt = readroute(list);
		return opt;
	}

	public static Opt readroute(ArrayList<String> list) {
		Pattern pattern = Pattern.compile("\\d+");
		Opt opt = new Opt();
		opt.resulttype = ResultType.OPT;

		for (int i = 0; i < list.size(); i++) {
			String string = list.get(i);
			if (string.startsWith("Route #")) {

				Matcher matche = pattern.matcher(string);

				if (!matche.find()) {
					throw new RuntimeException(
							"error in reading route! route:  " + string);
				}

				ArrayList<Integer> e = new ArrayList<Integer>();
				opt.routes.add(e);
				while (matche.find()) {
					e.add(Integer.parseInt(matche.group()));
				}
			} else if (string.startsWith("cost")) {

				opt.cost = Double.parseDouble(string.substring(5));

			} else {
				ArrayList<Integer> e = null;
				if (opt.routes.isEmpty()) {
					e = new ArrayList<Integer>();
					opt.routes.add(e);
				} else {
					e = opt.routes.get(opt.routes.size() - 1);
				}
				Matcher matche = pattern.matcher(string);
				while (matche.find()) {
					e.add(Integer.parseInt(matche.group()));
				}
			}

		}
		return opt;
	}

	public static Opt readroute2(ArrayList<String> list) {
		Pattern pattern = Pattern.compile("\\d+");
		Opt opt = new Opt();
		opt.resulttype = ResultType.HEU;

		for (int i = 0; i < list.size(); i++) {
			String string = list.get(i);
			if (string.startsWith("Route ")) {
				ArrayList<Integer> e = new ArrayList<Integer>();
				opt.routes.add(e);
				continue;
			} else if (string.startsWith("End of routes")) {
				break;
			} else {
				ArrayList<Integer> e = null;
				e = opt.routes.get(opt.routes.size() - 1);
				Matcher matche = pattern.matcher(string);
				while (matche.find()) {
					int parseInt = Integer.parseInt(matche.group());
					if (parseInt != 0)
						e.add(parseInt);
				}
			}
		}
		return opt;
	}
}
